<template>
  <div>
    <el-header>
      <el-button type="primary" @click="handleAdd">添加菜品</el-button>

    </el-header>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="菜品id"
          width="120">
        <template slot-scope="scope">{{ scope.row.productId }}</template>
      </el-table-column>
      <el-table-column
          prop="productType"
          label="类型"
          width="120">
        <template slot-scope="scope">{{ scope.row.productType }}</template>
      </el-table-column>
      <el-table-column
          prop="productName"
          label="菜品名称"
          show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.productName }}</template>

      </el-table-column>
      <el-table-column
          prop="productUrl"
          label="菜品图片"
          show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.productUrl }}</template>
      </el-table-column>
      <el-table-column
          prop="productPrice"
          label="菜品价格"
          show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.productPrice }}</template>

      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">修改
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--表单部分-->
    <!--修改菜品：-->
    <el-dialog title="修改菜品信息" :visible.sync="dialogUpdateFormVisible" width="500px">
      <el-form ref="form" :model="updateProductForm" label-width="80px" size="mini" :rules="rules">
        <el-form-item label="菜品类型" prop="productType">
          <el-input v-model="updateProductForm.productType"></el-input>
        </el-form-item>
        <el-form-item label="菜品名称" prop="productName">
          <el-input v-model="updateProductForm.productName"></el-input>
        </el-form-item>

        <el-form-item label="菜品图片" prop="productUrl">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8081/upload/product"
              name="img"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleUpdateAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="updateProductForm.productUrl" :src="updateProductForm.productUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="菜品价格" prop="productPrice">
          <el-input v-model="updateProductForm.productPrice"></el-input>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="onUpdateFormSubmit">提交</el-button>
          <el-button @click="onUpdateFormCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--添加菜品-->
    <el-dialog title="添加菜品信息" :visible.sync="dialogAddFormVisible" width="500px">
      <el-form ref="form" :model="addProductForm" label-width="80px" size="mini" :rules="rules">
        <el-form-item label="菜品类型" prop="productType">
          <el-input v-model="addProductForm.productType"></el-input>
        </el-form-item>
        <el-form-item label="菜品名称" prop="productName">
          <el-input v-model="addProductForm.productName"></el-input>
        </el-form-item>

        <el-form-item label="菜品图片" prop="productUrl">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8081/upload/product"
              name="img"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleUpdateAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="addProductForm.productUrl" :src="addProductForm.productUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="菜品价格" prop="productPrice">
          <el-input v-model="addProductForm.productPrice"></el-input>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="onAddFormSubmit">提交</el-button>
          <el-button @click="onAddFormCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-footer>
      <div class="block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[5, 10, 20]"
            :page-size="5"
            layout="sizes, prev, pager, next"
            :total=this.totalData>
        </el-pagination>
      </div>
    </el-footer>
  </div>


</template>

<script>
import {addProduct, deleteProduct, getCount, getProductList, updateProduct} from "@/API/ProductAPI";
import Message from "@/utils/message";

export default {
  name: 'ProductManager',
  data() {
    return {
      headers:{
        token:localStorage.getItem('token'),
      },
      dialogUpdateFormVisible: false,
      dialogAddFormVisible: false,
      totalData: 1,
      page: '1',
      pageSize: '5',

      tableData: [],
      multipleSelection: [],
      // 修改菜品表单
      updateProductForm: {
        productType: '',
        productName: '',
        productUrl: '',
        productPrice: '',
      },
      // 添加菜品表单
      addProductForm: {
        productType: '',
        productName: '',
        productUrl: '',
        productPrice: '',
      },
      thisProductId: '',
      // 表单规则(通用)
      rules: {
        productType: [
          {required: true, message: '请输入菜品类型', trigger: 'blur'}
        ],
        productName: [
          {required: true, message: '请输入菜品名称', trigger: 'blur'}
        ],
        productUrl: [
          {required: true, message: '请添加菜品图片', trigger: 'blur'}
        ],
        productPrice: [
          {required: true, message: '请输入菜品价格', trigger: 'blur'}
        ],
      },
      formLabelWidth: '120px',
    }
  },
  async mounted() {
    // Message.success(this, "菜品加载成功。");
    await this.loadTable();
    const countResult = await getCount();
    this.totalData = countResult.data;
  },
  methods: {
    // 加载表格
    async loadTable() {

      let result = await getProductList(this.page,this.pageSize);
      console.log(result.data)
      if (result.code === 1) {
        this.tableData = result.data;
        console.log(this.tableData)
      } else {
        Message.error(this, "菜品加载失败。");
      }
    },
    handleAdd() {
      this.dialogAddFormVisible = true;
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击修改触发
    handleEdit(index, row) {
      this.dialogUpdateFormVisible = true;
      this.updateProductForm.productType = row.productType;
      this.updateProductForm.productName = row.productName;
      this.updateProductForm.productPrice = row.productPrice;
      this.updateProductForm.productUrl = row.productUrl;
      this.thisProductId = row.productId;
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 调用删除接口,重新加载
        const result = await deleteProduct(row.productId);
        if (result.code === 1) {
          await this.loadTable();
          Message.success(this, "删除成功。");
        } else {
          Message.error(this, result.description);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        });
      });

    },
    async onAddFormSubmit() {
      const result = await addProduct(this.addProductForm);
      if (result.code === 1) {
        await this.loadTable();
        Message.success(this, "增加菜品成功。");
        this.dialogAddFormVisible = false;
      } else {
        Message.error(this, result.description);
      }
    },
    // 提交修改表单
    async onUpdateFormSubmit() {
      const result = await updateProduct(this.thisProductId, this.updateProductForm);
      if (result.code === 1) {
        await this.loadTable();
        Message.success(this, "修改成功。");
        this.dialogUpdateFormVisible = false;
      } else {
        Message.error(this, result.description);
      }
    },
    // 取消修改
    onAddFormCancel() {
      this.dialogAddFormVisible = false;
    },
    onUpdateFormCancel() {
      this.dialogUpdateFormVisible = false;
    },
    // 更新上传
    handleUpdateAvatarSuccess(res) {
      if(res.code === 1){
        this.addProductForm.productUrl = res.data;
        this.updateProductForm.productUrl = res.data;
      }



    },
    // 添加上传

    // 上传前校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    async handleSizeChange(val) {
      this.pageSize = val;
      await this.loadTable();
    },
    async handleCurrentChange(val) {
      this.page = val;
      await this.loadTable();
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>